
UE.registerUI('caselink', function(editor, uiName) {
    //register a caseLink button
    //注册按钮执行时的command命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
        execCommand: function() {
            createCaseToChoose();
        }
    });
    //创建一个button
    var btn = new UE.ui.Button({
        //按钮的名字
        name: uiName,
        //提示
        title: uiName,
        //添加额外样式，指定icon图标，这里默认使用一个重复的icon
        cssRules: 'background-position: -500px -20px;',
        //点击时执行的命令
        onclick: function() {
            //这里可以不用执行命令,做你自己的操作也可
            editor.execCommand(uiName);
        }
    });
    //当点到编辑内容上时，按钮要做的状态反射
    editor.addListener('selectionchange', function() {
        var state = editor.queryCommandState(uiName);
        if (state == -1) {
            btn.setDisabled(true);
            btn.setChecked(false);
        } else {
            btn.setDisabled(false);
            btn.setChecked(state);
        }
    });
    //因为你是添加button,所以需要返回这个button
    return btn;
});

UE.registerUI('imagelink', function(editor, uiName) {
    //register a imageLink button
    //注册按钮执行时的command命令，使用命令默认就会带有回退操作
    editor.registerCommand(uiName, {
        execCommand: function() {
            imageLink();
        }
    });
    //创建一个button
    var btn = new UE.ui.Button({
        //按钮的名字
        name: uiName,
        //提示
        title: uiName,
        //添加额外样式，指定icon图标，这里默认使用一个重复的icon
        cssRules: 'background-position: -460px -20px;',
        //点击时执行的命令
        onclick: function() {
            //这里可以不用执行命令,做你自己的操作也可
            editor.execCommand(uiName);
        }
    });
    //当点到编辑内容上时，按钮要做的状态反射
    editor.addListener('selectionchange', function() {
        var state = editor.queryCommandState(uiName);
        if (state == -1) {
            btn.setDisabled(true);
            btn.setChecked(false);
        } else {
            btn.setDisabled(false);
            btn.setChecked(state);
        }
    });
    //因为你是添加button,所以需要返回这个button
    return btn;
});

function createCaseToChoose(){
    var case_tree = document.getElementById('case_tree');
    var ue = UE.getEditor('editor');
    var range = ue.selection.getRange();
    range.select();
    var txt = ue.selection.getText();
    var doc = range.document;
    var as = doc.getElementsByTagName("a");
    var url = "";
    if(as.length>0 && as[as.length-1].id==txt){
        //alert(as[as.length-1].rel);
        url = "/CooperateWeb/case/caseLink?checkIds=" + as[as.length-1].rel;
    }else{
        url = "/CooperateWeb/case/caseLink?checkIds=0";
    }
    if(txt==null || txt==""){
        alert("您未选中文本");
        return;
    }
    $.ajax({
        url:url,
        success:function(result){
            if(result.successful){
                var casedata = eval("("+result.message+")");
                $('#case_tree').tree({
                    checkbox:true,
                    onlyLeafCheck: true,
                    animate:true,
                    lines:true,
                    data: casedata,
                    formatter: function(node) {
                        return node.text + "-";
                    }
                });
                $('#caseLinkWindow').window('open');
                var saveCaseLink = document.getElementById('caseLink_ok');
                saveCaseLink.setAttribute("onclick","saveCaseLink('"+txt+"')");
            }
        }
    });
}

function imageLink(){
    var ue = UE.getEditor('editor');
    var range = ue.selection.getRange();
    range.select();
    var txt = ue.selection.getText();
    if(txt==null || txt==""){
        alert("您未选中文本");
        return;
    }
    imageLinkPre(txt);
    $("#imageLinkWindow").window('open');
}

function imageLinkPre(txt){
    //clear image table
    var table = document.getElementById("imageTable");
    table.innerHTML = "";
    var ue = UE.getEditor('editor');
    var range = ue.selection.getRange();
    var doc = range.document;
    var as = doc.getElementsByTagName("a");

    var imageLinkAdd = document.getElementById('imageLinkAdd');
    var imageLinkSave = document.getElementById('imageLinkSave');
    imageLinkAdd.setAttribute('onclick',"addImage()");
    imageLinkSave.setAttribute("onclick","saveImage('"+txt+"')");

    if(as.length>0 && as[as.length-1].id==txt){
        var rels = as[as.length-1].rel;
        var images = rels.split(",");
        for(var i=0;i<images.length;i++){
            var tr = document.createElement("tr");
            tr.setAttribute("id",i);
            var td1 = document.createElement("td");
            var td2 = document.createElement("td");
            td1.innerHTML = images[i];
            td2.innerHTML = "<a href=\"#\" onclick=\"delImage("+i+")\">delete</a>";
            tr.appendChild(td1);
            tr.appendChild(td2);
            table.appendChild(tr);
        }
    }

}

function addImage(){
    var table = document.getElementById("imageTable");
    var count = 0;
    if(table.rows.length > 0){
        count = parseInt(table.rows[table.rows.length - 1].id) + 1;
    }
    var e = document.createElement("input");
    e.setAttribute("type","file");
    e.setAttribute("id","file"+ count);
    e.setAttribute("name","file");
    e.setAttribute("style","display:none");
    e.setAttribute("accept","image/*");
    e.setAttribute("onchange","changeImage("+count+")");
    document.getElementById("imageLinkWindow").appendChild(e);
    e.click();
}

function changeImage(count){
    var e = document.getElementById("file"+ count);
    var filepath = e.value;

    filepath = filepath.substring(filepath.lastIndexOf("\\")+1);
    var table = document.getElementById("imageTable");
    var i = table.rows.length;
    var tr = document.createElement("tr");
    tr.setAttribute("id", count);
    var td1 = document.createElement("td");
    td1.setAttribute("width","70%");
    var td2 = document.createElement("td");
    td2.setAttribute("width","30%");
    td1.innerHTML = filepath;
    td2.innerHTML = "<a href=\"#\" onclick=\"delImage("+i+")\">delete</a>";
    tr.appendChild(td1);
    tr.appendChild(td2);
    table.appendChild(tr);
}

function delImage(i){
    var table = document.getElementById("imageTable");
    var rows = table.rows.length;
    for(var row=i+1;row<rows;row++){
        //table.rows[row].setAttribute("id",row-1);
        table.rows[row].getElementsByTagName("a")[0].setAttribute("onclick","delImage("+(row-1)+")");
    }
    var file_id = table.rows[i].id;
    table.deleteRow(i);
    var e = document.getElementById("file"+ file_id);
    var windowObj = document.getElementById("imageLinkWindow");
    if(e!=null)
        windowObj.removeChild(e);
}

function saveImage(txt){
    var ids = [];
    var ids_index = 0;
    var table = document.getElementById("imageTable");
    var value = "";
    for(var i=0;i<table.rows.length;i++){
        value += "," + table.rows[i].cells[0].innerHTML;
    }
    for(var count=0;count<20;count++) {
        var e = document.getElementById("file" + count);
        if (e != null) {
            ids[ids_index++] = e.id;
        }
    }
    $.ajaxFileUpload({
        url:"/CooperateWeb/upload/uploadPic",
        secureuri:false,
        fileElementId:ids,
        dataType:'json',
        success:function(data,status){
            if(data){
                //$.messager.alert("提示",data.result,"info");
            }else{
                $.messager.alert("提示",data.result,"error");
            }
        },
        error:function(data,status,e){
        }
    });
    var ue = UE.getEditor('editor');
    var range = ue.selection.getRange();
    var doc = range.document;
    var as = doc.getElementsByTagName("a");
    if(as.length>0 && as[as.length-1].id==txt){
        as[as.length-1].setAttribute("rel",value.substring(1));
    }else{
        ue.execCommand('inserthtml','<a id="'+txt+'" class="image_link" href="#" rel="'+value.substring(1)+'">'+txt+'</a>');
    }
    $('#imageLinkWindow').window('close');
}

function saveCaseLink(txt){
    var cases = $('#case_tree').tree('getChecked');
    var ids = "";
    for(var i=0;i<cases.length;i++){
        ids = ids + "," + cases[i].id;
    }
    var ue = UE.getEditor('editor');
    var range = ue.selection.getRange();
    var doc = range.document;
    var as = doc.getElementsByTagName("a");
    if(as.length>0 && as[as.length-1].id==txt){
        as[as.length-1].setAttribute("rel",ids.substring(1));
    }else{
        ue.execCommand('inserthtml','<a id="'+txt+'" class="case_link" href="#" rel="'+ids.substring(1)+'">'+txt+'</a>');
    }
    $('#caseLinkWindow').window('close');
}

function cancelCaseLink(){
    $('#caseLinkWindow').window('close');
}